<!--
*@Author: zt
*@Description: 动态表单创建
*@Date: 2024-09-10
-->
<template>
  <u-dialog
    v-bind="$attrs"
    @submit="submit"
    @close="close"
    :hideBtns="route.params.pType == '2' ? ['submit'] : []"
    :title="form.contractNo"
  >
    <u-flow-tab
      activeKey="1"
      :show="isValue(form.status) && form.ishaveaudit == 1"
      :params="{ type: 'form_apply', ...form, keyid: attrs.keyid }"
      :isAudit="form.status == 2"
      :isAuditPage="route.params.pType == '2'"
      v-bind="$attrs"
      ref="auditRef"
    >
      <a-tab-pane key="1" tab="基本信息">
        <div class="contain">
          <div class="formBox" style="background-color: #fff; overflow-y: auto">
            <a-form :model="form" class="f-w-100">
              <!-- 动态表单组件 -->
              <a-row class="f-w-100" :gutter="[30]">
                <a-col
                  :span="8"
                  v-for="(item, index) in form.list"
                  :key="index"
                >
                  <a-form-item
                    :label="form.list[index].name"
                    :name="item.name"
                    :rules="item.rule"
                    class="active"
                  >
                    <!-- 输入框 -->
                    <u-input
                      v-if="item.itemType == 'input'"
                      v-model:value="item.value"
                      :addonAfter="item.addonAfter"
                      :addonBefore="item.addonBefore"
                      :allowClear="item.allowClear"
                      :bordered="item.bordered"
                      :clearIcon="item.clearIcon"
                      :placeholder="item.placeholder"
                      :disabled="item.disabled"
                      :maxlength="item.maxlength"
                      :prefix="item.prefix"
                      :showCount="item.showCount"
                      :status="item.status"
                      :size="item.size"
                      :suffix="item.suffix"
                      :type="item.type"
                    ></u-input>

                    <!-- 下拉框 -->
                    <u-select
                      v-if="item.itemType == 'select'"
                      v-model:value="item.value"
                      :allowClear="item.allowClear"
                      :autoClearSearchValue="item.autoClearSearchValue"
                      :autofocus="item.autofocus"
                      :bordered="item.bordered"
                      :clearIcon="item.clearIcon"
                      :defaultActiveFirstOption="item.defaultActiveFirstOption"
                      :defaultOpen="item.defaultOpen"
                      :disabled="item.disabled"
                      :popupClassName="item.popupClassName"
                      :dropdownMatchSelectWidth="item.dropdownMatchSelectWidth"
                      :filterOption="item.filterOption"
                      :firstActiveValue="item.firstActiveValue"
                      :mode="item.mode"
                      :options="item.options"
                      :fieldNames="{
                        label: 'label',
                        value: 'id',
                        options: 'children',
                      }"
                      :placeholder="item.placeholder"
                    ></u-select>

                    <!-- 开关 -->
                    <a-switch
                      v-if="item.itemType == 'switch'"
                      v-model:checked="item.value"
                      :autofocus="item.autofocus"
                      :checkedChildren="item.checkedChildren"
                      :checkedValue="item.checkedValue"
                      :disabled="item.disabled"
                      :loading="item.loading"
                      :size="item.size"
                      :unCheckedChildren="item.unCheckedChildren"
                      :unCheckedValue="item.unCheckedValue"
                    />

                    <!-- 树 -->
                    <u-tree
                      v-if="item.itemType == 'tree'"
                      :showSearch="item.showSearch"
                      :checkable="item.checkable"
                      v-model:checkedKeys="item.checkedKeys"
                      v-model:expandedKeys="item.expandedKeys"
                      v-model:selectedKeys="item.selectedKeys"
                      :disabled="item.disabled"
                      :fieldNames="{
                        title: 'name',
                        key: 'keyid',
                        children: 'children',
                      }"
                      :multiple="item.multiple"
                      :treeData="item.treeData"
                    ></u-tree>

                    <!-- 上传 -->
                    <u-field-upload
                      v-if="item.itemType == 'upload'"
                      v-model:value="item.value"
                      :fileParams="{
                        bucket: 'DVC',
                        biztype: routeArr[routeArr.length - 1],
                      }"
                      :disabled="item.disabled"
                      :multiple="item.multiple"
                    ></u-field-upload>

                    <!-- 复选框 -->
                    <a-checkbox-group
                      v-if="item.itemType == 'checkbox'"
                      v-model:value="item.value"
                      :disabled="item.disabled"
                      :options="item.options"
                    />

                    <!-- 时间选择 -->
                    <u-date-picker
                      v-if="item.itemType == 'datepicker'"
                      v-model:value="item.value"
                      :valueFormat="item.valueFormat"
                      :format="item.valueFormat"
                      :disabled-date="
                        item.disabledDate ? item.disabledDate : () => false
                      "
                      :showTime="
                        item.valueFormat == 'YYYY-MM-DD HH:mm' ? true : false
                      "
                      :disabled="item.disabled"
                    ></u-date-picker>

                    <!-- 单选框 -->
                    <a-radio-group
                      v-if="item.itemType == 'radio'"
                      v-model:value="item.value"
                      :options="item.options"
                      :disabled="item.disabled"
                    />

                    <!-- 级联框 -->
                    <u-cascader
                      v-if="item.itemType == 'cascader'"
                      v-model:value="item.value"
                      :fieldNames="{ title: 'label', key: 'value' }"
                      :multiple="item.multiple"
                      :disabled="item.disabled"
                      :showSearch="item.showSearch"
                      :searchValue="item.searchValue"
                      :bordered="item.bordered"
                      :options="item.options"
                    ></u-cascader>
                  </a-form-item>
                </a-col>
              </a-row>
            </a-form>
          </div>
        </div>
      </a-tab-pane>
    </u-flow-tab>
    <template #footerBefore>
      <template
        v-if="
          route.params.pType == '2' &&
          form.status == '2' &&
          $attrs['isAudited'] == true
        "
      >
        <u-icon-button itype="approve" @click="auditAbout('2')">
          批准
        </u-icon-button>
        <u-icon-button itype="clsoe" @click="auditAbout('3')">
          退回
        </u-icon-button>
      </template>
    </template>
  </u-dialog>
</template>

<script lang="ts" setup>
import {
  computed,
  nextTick,
  reactive,
  ref,
  toRaw,
  toRefs,
  UnwrapRef,
  useAttrs,
  watch,
} from 'vue';
import { FormInstance } from 'ant-design-vue'; // 确保你已经安装了 ant-design-vue
import { alertC, isValue } from '@/util/common';
import { storeToRefs } from 'pinia';
import { useBaseStore } from '@/store';
import { dymicTFormdataArr } from './enmu.ts';
import { useAuditAbout, IAuditParams } from '@/hooks/useAudit';
import { useRoute } from 'vue-router';
import * as dynamicFormsItemApi from '@/service/emergency/dynamicFormsItem/index';
import * as dynamicFormsApi from '@/service/emergency/dynamicForms/index';

const { ISPROXY } = storeToRefs(useBaseStore());
const emits = defineEmits(['success', 'close']);
const attrs = useAttrs();
const route = useRoute();
const routeArr = route.path.split('/');
const formRef = ref<FormInstance>();
let auditRef = ref();

const ruleForm = ref<FormInstance | null>(null);
const SForm = reactive({
  fkmoduleid: '',
  ishaveaudit: 0,
  modulename: '',
  keyid: '',
});

let form = ref({
  contractNo: '',
  list: [],
  status: '',
  ishaveaudit: '',
});

// 提交表单
const submit = async () => {
  let tform1 = <any>{};
  form.value.list.map(e => {
    dymicTFormdataArr.map(index => {
      if (e.id == index) {
        tform1[index] = e.value;
      }
    });
  });

  tform1.status = 1;
  tform1.fkdycform = routeArr[routeArr.length - 1];
  if (attrs.keyid) {
    tform1.keyid = attrs.keyid;
  }

  const url = attrs.keyid ? 'updata' : 'create';
  const res = await dynamicFormsItemApi[url](tform1);

  if (res.code == 0) {
    alertC(res.msg, 'success');
    form.value.list = [];
    emits('success');
    return;
  } else {
    alertC(res.msg, 'error');
    return;
  }
};

const close = () => {
  form.value.list = [];
  form.value = {};
  emits('close');
};

// 回显表单数据
const getHx = async () => {
  await getDetails();
  const res = await dynamicFormsItemApi.query(attrs.keyid);
  if (res.code == 0) {
    for (let key in res.data) {
      form.value.list.map(e => {
        if (e.id == key) {
          e.value = res.data[key];
          if (e.itemType == 'switch') {
            e.value = e.value == 'true' ? true : false;
          }
        }
      });
    }
    form.value = { ...form.value, ...res.data };
  }
};

// 上报、审核、退回
const auditAbout = async (type: string) => {
  const auditParams: IAuditParams = {
    type: 'form_apply',
    selDatas: [form.value],
    confirm: false,
    isDialog: false,
  };
  try {
    const res = await useAuditAbout(type, auditParams, auditRef);
    if (res.error == 200) {
      form.value.list = [];
      form.value = {};
      emits('success');
    }
  } catch (error) {}
};

//表单渲染内容
const getDetails = async () => {
  const res = await dynamicFormsApi.query(routeArr[routeArr.length - 1]);
  if (res.code == 0) {
    form.value = JSON.parse(res.data.formjson);
    form.value.ishaveaudit = res.data.ishaveaudit;
  }
};

watch(
  () => attrs.open,
  async (nav, val) => {
    if (nav == true) {
      await getDetails();
      if (attrs.keyid) {
        await getHx();
      }
    }
  },
  { immediate: true }
);
</script>

<style scoped lang="scss">
/* 你的样式 */
.contain {
  margin: 0;
  padding: 0;
  display: flex;
  justify-content: space-between;

  .formButtonBox {
    height: 80vh;

    border-radius: 2%;
    margin-right: 100px;

    .formButton {
      display: flex;
      align-items: center;
      justify-content: center;
    }
  }

  .formBox {
    width: 100%;
    // padding: 2vw;
    border-radius: 2%;
    // background-color: #fff;
    height: 100%;
    box-sizing: border-box;
    // min-height: 80vh;
    // margin-right: 100px;

    .formButton {
      display: flex;
      align-items: center;
      justify-content: center;
    }
  }

  .formItemBox {
    width: 800px;
    padding: 2vw;
    border-radius: 2%;
    // background-color: #fff;
    height: 100%;
    box-sizing: border-box;
    min-height: 80vh;

    .formButton {
      display: flex;
      align-items: center;
      justify-content: center;
    }
  }
}
</style>
